<template>
  <a-tabs v-model:active-key="activeKey" type="editable-card" @edit="onEdit">
    <a-tab-pane v-for="pane in panes" :key="pane.key" :tab="pane.title" :closable="pane.closable">
      <viewItem :url="pane.url" />
    </a-tab-pane>
  </a-tabs>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import viewItem from './viewItem.vue'

const panes = ref<{ title: string; url: string; key: string; closable?: boolean }[]>([{ title: 'Tab 1', url: 'http://www.baidu.com', key: '1', closable: false }])

const activeKey = ref(panes.value[0].key)

const newTabIndex = ref(0)

const add = (url = '') => {
  activeKey.value = `newTab${++newTabIndex.value}`
  panes.value.push({ title: 'New Tab', url, key: activeKey.value })
}

const remove = (targetKey: string) => {
  let lastIndex = 0
  panes.value.forEach((pane, i) => {
    if (pane.key === targetKey) {
      lastIndex = i - 1
    }
  })
  panes.value = panes.value.filter((pane) => pane.key !== targetKey)
  if (panes.value.length && activeKey.value === targetKey) {
    if (lastIndex >= 0) {
      activeKey.value = panes.value[lastIndex].key
    } else {
      activeKey.value = panes.value[0].key
    }
  }
}

const onEdit = (targetKey: string | MouseEvent, action: string) => {
  if (action === 'add') {
    add()
  } else {
    remove(targetKey as string)
  }
}

window.electron.ipcRenderer.on('webview-url', (_event, data) => {
  console.log('newTab', data.url)
  add(data.url)
})
</script>

<style scoped lang="scss">
.ant-tabs {
  height: 100%;
  // /deep/ .ant-tabs-content {
  //   height: 100%;
  // }
  // vue3写法
}

:deep .ant-tabs-nav {
  margin-bottom: 0;
}

:deep .ant-tabs-content {
  height: 100%;
}
</style>
